﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Account : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if ((Session["username"] == null) || (Session["username"].ToString().CompareTo("") == 0))
        {
            Response.Redirect("Login.aspx?Redirect=Account"); 
        }
        else
        {
            //Load Current Avatar
            String username = Session["username"].ToString();
            var Client = new BusinessTier.DataManipulation();
            img1.ImageUrl = (string)Client.LoadAvatar(username);
        }
    }
    
    /*
     * Sends the request to change the user's avatar to the image they selected
     */
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (upload_file.HasFile)
        {
            String file_type = upload_file.PostedFile.ContentType;

            //check file type is an image (.jpg)
            if (file_type.StartsWith("image"))
            {
                byte[] input = upload_file.FileBytes;
                String username = Session["username"].ToString();

               var Client = new BusinessTier.DataManipulation();

                //Response.BinaryWrite(input);
                String response = (string)Client.ChangeAvatar(input, username);

                //Process response from service
                if (response.CompareTo("200") == 0)
                {
                    //Refresh the page to show new avatar
                    Response.Redirect(Page.Request.Url.ToString(), true);
                }
                else
                {
                    Result.Text = ("\nFailed to upload your new avatar");
                }
            }
            else
            {
                Result.Text = "You need to upload an image for your avatar.";
            }

        }
    }
}
